"""
@File    : runMain.py
@Time    : 2019/11/26 16:23
@Author  : LiuFeiYu
@Email   : Liufeiyu@sunrise.net
@Software: PyCharm
"""
from Common.JiraHelper import GetJiraData
from Script.JiraScript import jira_switch
from Settings.Config import Config
from Constant.ApiConstant import ErrorApiNumber
from Constant import API_ERROR_RESPONSE_DATA
from Common.DingTalkHelper import DingTalkSendMsg
from Common import Info, ShellHelper, LogHelper
from Controller import releseController, testController
import sys
import pytest


def run_pytest():
    conf = Config()
    log = LogHelper.MyLog()
    shell = ShellHelper.Shell()
    xml_report_path = conf.xml_report_path
    html_report_path = conf.html_report_path
    # pytest运行
    args = ['-s', '-q', '--no-print-logs', '--alluredir', xml_report_path]
    pytest.main(args)
    cmd = 'allure generate %s -o %s' % (xml_report_path, html_report_path)
    # 发送钉钉消息
    DingTalkSendMsg().send_msg_by_markdown(true_num=ErrorApiNumber.API_TRUE_RESPONSE_NUMBER,
                                           err_num=ErrorApiNumber.API_ERROR_RESPONSE_NUMBER)

    try:
        shell.invoke(cmd)
        if jira_switch == "1":
            error_num = ErrorApiNumber.API_ERROR_RESPONSE_NUMBER
            true_num = ErrorApiNumber.API_TRUE_RESPONSE_NUMBER
            accuracy_rate = "%.2f" % (true_num / (true_num + error_num))
            # 自动提交问题单,如果错误接口数量超过10或者错误率低于95%,则不自动提交问题单，否则自动提交问题单
            if ErrorApiNumber.API_ERROR_RESPONSE_NUMBER >= 10 or float(accuracy_rate) < 0.95:
                pass
            else:
                for error in API_ERROR_RESPONSE_DATA:
                    GetJiraData().create_issue(project_id=error['project_id'],
                                               summary=error['summary'],
                                               description=error['description'],
                                               assignee=error['assignee'])

    except Exception:
        log.error_msg('执行用例失败，请检查环境配置')
        raise


if __name__ == '__main__':
    # 获取环境参数,外部传入,0为测试环境,1为线上环境
    para_1 = sys.argv

    if len(para_1) > 1:
        if para_1[1] == "0":
            print("正在配置测试环境相关参数...")
            testController.TestController().init_config()
            run_pytest()
        elif para_1[1] == "1":
            print("正在配置线上环境相关参数...")
            releseController.ReleaseController().init_config()
            run_pytest()
        elif para_1[1] == "-help":
            print(Info())
        else:
            print('输出环境参数错误！请输入-help查看')
    else:
        print('输出环境参数错误！请输入-help查看')
